import 'dart:io';

import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'login.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'constants.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MaterialApp(home: ScanAttendancePage()));
}

class ScanAttendancePage extends StatefulWidget {
  const ScanAttendancePage({Key? key});

  @override
  State<ScanAttendancePage> createState() => _ScanAttendancePageState();
}

class _ScanAttendancePageState extends State<ScanAttendancePage> {
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  TextEditingController _manualInputController = TextEditingController();
  Barcode? result;
  QRViewController? controller;

  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller!.pauseCamera();
    } else if (Platform.isIOS) {
      controller!.resumeCamera();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Text(
          '扫描签到',
          style: TextStyle(fontSize: 20, color: Colors.black),
        ),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black54,
          ),
          onPressed: () {
            // 返回按钮功能
            Navigator.pop(context);
          },
        ),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            flex: 6,
            child: Container(
              color: Colors.black,
              child: QRView(
                key: qrKey,
                onQRViewCreated: _onQRViewCreated,
              ),
            ),
          ),
          Expanded(
            flex: 4,
            child: Container(
              color: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '无法识别? 手动输入',
                    style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 16),
                  Container(
                    width: double.infinity,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Color.fromARGB(255, 228, 236, 233),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: TextField(
                      controller: _manualInputController,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.symmetric(horizontal: 10),
                        hintText: '请输入签到码',
                        alignLabelWithHint: true,
                      ),
                    ),
                  ),
                  SizedBox(height: 16),
                  Container(
                    width: double.infinity,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Color.fromARGB(255, 179, 202, 193),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: TextButton(
                      onPressed: () {
                        // 点击按钮触发的操作
                        String inputText = _manualInputController.text;
                        signIn(inputText);
                      },
                      child: Text(
                        '确认',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
      });
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  Future<void> signIn(String signCode) async {
    String jwtToken = await retrieveJwtToken('access_token');
    if (jwtToken == '' && !isJwtExpired(jwtToken)) {
      print('No JWT token found or expire.');
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Login()),
      );
      return;
    }
    String serverUrl = AppConstants.serverUrl;

    try {
      var response = await http.post(Uri.parse('$serverUrl/v1/attendance'),
          headers: {
            "Content-Type": "application/json",
            "Authorization": "Bearer $jwtToken"
          },
          body: jsonEncode({"sign_code": "$signCode"}));

      if (response.statusCode == 200) {
        // Handle the response
        _alertDialog("签到成功", "成功签到");
        print("Sign-in successful");
      } else {
        // Handle error
        print("Failed to sign in: ${response.body}");
      }
    } catch (e) {
      // Handle exception
      print("Error occurred: $e");
    }
  }

  _alertDialog(String title, String content) async {
    await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text(title),
            content: Text(content),
            actions: <Widget>[
              TextButton(
                  onPressed: () {
                    // 在取消按钮点击时关闭对话框，不返回任何结果
                    Navigator.pop(context);
                  },
                  child: Text(
                    '取消',
                    style: TextStyle(color: Colors.grey),
                  )),
              TextButton(
                onPressed: () {
                  // 在确认按钮点击时关闭对话框，不返回任何结果
                  Navigator.pop(context);
                },
                child: Text(
                  '确定',
                  style: TextStyle(color: Colors.blue),
                ),
              ),
            ],
          );
        });
  }
}
